//
//  AccountManagementViewController.m
//  HAODE
//
//  Created by panquanReabam.com on 15/9/15.
//  Copyright (c) 2015年 reabam.com. All rights reserved.
//

#import "AccountManagementViewController.h"
#import "RDVTabBarController.h"
#import "UpdateThePasswordViewController.h"
#import "TheLoginViewController.h"
#import "HttpRequest.h"
#import "VPImageCropperViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "UpYun.h"
#import "UIButton+WebCache.h"
#import "TheEditingViewController.h"
#import "ForgotPasswordViewController.h"
@interface AccountManagementViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate, UITextViewDelegate,UIImagePickerControllerDelegate,UIAlertViewDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UITextFieldDelegate,VPImageCropperDelegate,TheEditingViewControllerDelegate>

{
    
    NSArray *array;
    NSArray *array1;
    UIButton *imageView;
    NSString* userName;
    NSString* userCode;
    NSString* sex;
    NSString* tel;
    NSString* companyName;
    NSString* userType;
    NSString* headImageUrl;
    NSString*headImage;
    UITableView*table;
    
}
@property (nonatomic, strong) UIImageView *portraitImageView;
@property (nonatomic,strong) UIImagePickerController *ipc;
@property (strong, nonatomic) UIImage *sendImage;
@end

@implementation AccountManagementViewController
@synthesize mDelegate;
- (void)viewDidDisappear:(BOOL)animated

{
    
    [super viewDidDisappear:animated];
    
    
    
    self.navigationController.delegate = nil;
    
}
-(void)BackAction:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.delegate = self;
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[[UIImage alloc] init];
    
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UIButton*sxBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 0.0, 35, 35)];
    [sxBtn setTitle:@"保存" forState:UIControlStateNormal];
    [sxBtn setTitleColor:luseColor forState:UIControlStateNormal];
    sxBtn .titleLabel.font=[UIFont systemFontOfSize:16];
    [sxBtn addTarget:self action:@selector(addProduct:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* myBtnBtn = [[UIBarButtonItem alloc] initWithCustomView:sxBtn];
    self.navigationItem.rightBarButtonItem = myBtnBtn;
    

    
    
}
-(void)secondViewController:(TheEditingViewController *)secondViewController updateUserNameText:(NSString *)userNameStr updateSexStr:(NSString *)sexStr updateMemoStr:(NSString *)memoStr{

        userName = userNameStr;
        sex = sexStr;
    
    if ([sex isEqualToString:@"(null)"]) {
        sex =@"";
    }
        [self  tabelView];


}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
    [params setValue:@"member" forKey:@"uploadType"];
    
    
    [HttpRequest requestData:@"Common/GetUpyunFormParams" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                NSString*policy=[severDataDict.dataDict objectForKey:@"policy"];
                NSString*signature=[severDataDict.dataDict objectForKey:@"signature"];
                NSString*action=[severDataDict.dataDict objectForKey:@"action"];
                [user setObject:signature forKey:@"signature"];
                [user setObject:policy forKey:@"policy"];
                [user setObject:action forKey:@"action"];
                [user synchronize];
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];

    
    
    self.title = @"账户管理";
    
    
    
    
    array = @[@"头像",@"姓名",@"性别",@"手机号",@"修改密码"];
   
    
    NSUserDefaults *userDefault=[NSUserDefaults standardUserDefaults];
    headImageUrl = [userDefault objectForKey:@"headImageUrl"];
    headImage= [userDefault objectForKey:@"headImage"];
    NSLog(@"---%@",headImage);
    sex = [userDefault objectForKey:@"sex"];
    userName = [userDefault objectForKey:@"userName"];
    userCode = [userDefault objectForKey:@"userCode"];
    companyName = [userDefault objectForKey:@"companyName"];
    userType = [userDefault objectForKey:@"userTypeName"];
    [self tabelView];
}
-(void)tabelView{
    [table removeFromSuperview];
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:table];

    [table reloadData];
}



#pragma mark--TableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1 ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    
    cell.textLabel.text = [array objectAtIndex:indexPath.row];
    cell.textLabel.font=[UIFont systemFontOfSize:15];
    cell.textLabel.textColor=[UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1];
    
    
    if ([[array objectAtIndex:indexPath.row]isEqualToString:@"头像"]) {
        
        imageView = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-90, 6, 132/2, 132/2)];
        imageView.layer.masksToBounds = YES;
        [imageView setImageWithURL:[NSURL URLWithString:headImageUrl] placeholderImage:[UIImage imageNamed:@"touxiang_weidenglu"]];
        imageView.layer.cornerRadius = 132/2/2;
        imageView.contentMode = UIViewContentModeScaleToFill;
        imageView.userInteractionEnabled=NO;
        UIImage *img=[UIImage imageNamed:@"logoyuanhuansss"];
        UIImage *tinted = [img rt_tintedImageWithColor:qianhuiColor];
//        cell.accessoryView=imageView;
        [cell.contentView addSubview:imageView];
        UIImageView* image=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 145/2,  145/2)];
        image.image=tinted;
        image.center=imageView.center;
        [cell.contentView addSubview:image];
      
    }
    if ([[array objectAtIndex:indexPath.row]isEqualToString:@"姓名"]) {
        
        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-205, 0, 160, 55)];
        label.text=[NSString stringWithFormat:@"%@",userName];
        label.textAlignment=NSTextAlignmentRight;
        label.textColor=zhonghuiColor; label.font=[UIFont systemFontOfSize:  15];
        [cell.contentView addSubview:label];
        UIButton*jiantou = [[UIButton alloc]init];
        jiantou.frame = CGRectMake(ScreenWidth-40,12.5, 30, 30);
        [jiantou setImage:[UIImage imageNamed:@"shouqi"] forState:UIControlStateNormal];
        jiantou.userInteractionEnabled=NO;
        [cell.contentView addSubview:jiantou];
    }
    
    if ([[array objectAtIndex:indexPath.row]isEqualToString:@"性别"]) {
        
        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-205, 0, 160, 55)];
        label.text=sex;
        label.textAlignment=NSTextAlignmentRight;
        label.textColor=zhonghuiColor;
        label.font=[UIFont systemFontOfSize:  15];
        [cell.contentView addSubview:label];
        UIButton*jiantou = [[UIButton alloc]init];
        jiantou.frame = CGRectMake(ScreenWidth-40,12.5, 30, 30);
        jiantou.userInteractionEnabled=NO;
        [jiantou setImage:[UIImage imageNamed:@"shouqi"] forState:UIControlStateNormal];
        [cell.contentView addSubview:jiantou];
    }
    
    if ([[array objectAtIndex:indexPath.row]isEqualToString:@"手机号"]) {
        
        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-205, 0, 160, 55)];
        label.text=[NSString stringWithFormat:@"%@",userCode];
        label.textAlignment=NSTextAlignmentRight;
        label.textColor=zhonghuiColor; label.font=[UIFont systemFontOfSize:  15];
        [cell.contentView addSubview:label];
        UIButton*jiantou = [[UIButton alloc]init];
        jiantou.frame = CGRectMake(ScreenWidth-40,12.5, 30, 30);
        [jiantou setImage:[UIImage imageNamed:@"shouqi"] forState:UIControlStateNormal];
        [cell.contentView addSubview:jiantou];
    }
    
    if ([[array objectAtIndex:indexPath.row]isEqualToString:@"我的门店"]) {
        
        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-205, 0, 160, 55)];
        label.text=[NSString stringWithFormat:@"%@",companyName];
        label.textAlignment=NSTextAlignmentRight;
        label.textColor=zhonghuiColor; label.font=[UIFont systemFontOfSize:  15];
        [cell.contentView addSubview:label];
        UIButton*jiantou = [[UIButton alloc]init];
        jiantou.frame = CGRectMake(ScreenWidth-40,12.5, 30, 30);
        [jiantou setImage:[UIImage imageNamed:@"shouqi"] forState:UIControlStateNormal];
        //        [cell.contentView addSubview:jiantou];
    }
    
    
    if ([[array objectAtIndex:indexPath.row]isEqualToString:@"我的身份"]) {
        
        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-205, 0, 160, 55)];
        label.text=[NSString stringWithFormat:@"%@",userType];
        label.textAlignment=NSTextAlignmentRight;
        label.textColor=zhonghuiColor; label.font=[UIFont systemFontOfSize:  15];
        [cell.contentView addSubview:label];
        UIButton*jiantou = [[UIButton alloc]init];
        jiantou.frame = CGRectMake(ScreenWidth-40,12.5, 30, 30);
        [jiantou setImage:[UIImage imageNamed:@"shouqi"] forState:UIControlStateNormal];
        //  [cell.contentView addSubview:jiantou];
    }
    if ([[array objectAtIndex:indexPath.row]isEqualToString:@"修改密码"]) {
        
        UIButton*jiantou = [[UIButton alloc]init];
        jiantou.frame = CGRectMake(ScreenWidth-40,12.5, 30, 30);
        jiantou.userInteractionEnabled=NO;
        [jiantou setImage:[UIImage imageNamed:@"shouqi"] forState:UIControlStateNormal];
        [cell.contentView addSubview:jiantou];
    }

    if (indexPath.row==0) {
        UILabel *lineLabel1=[[UILabel alloc] initWithFrame:CGRectMake(10, 80-0.40, ScreenWidth-20, 0.40)];
        lineLabel1.backgroundColor=qianhuiColor;
        [cell.contentView addSubview:lineLabel1];
        
    }else{
        
        if ([[array1 objectAtIndex:indexPath.row] count ]!=indexPath.row+1) {
            UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(10, 55-0.40, ScreenWidth-20, 0.3)];
            lineLabel.backgroundColor=qianhuiColor;
            [cell.contentView addSubview:lineLabel];
            
        }
    }
    
    if ([[array1 objectAtIndex:indexPath.row] count ] ==indexPath.row+1) {
        UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 55-0.40, ScreenWidth, 0.3)];
        lineLabel.backgroundColor=qianhuiColor;
        [cell.contentView addSubview:lineLabel];
        
    }
    return cell;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row==0) {
        return  80;
    }
    
    return  55;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell =(UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    if ([cell.textLabel.text isEqualToString:@"头像"]) {
        [self editPortrait];
        
    }
    if ([cell.textLabel.text isEqualToString:@"姓名"]) {
        
        TheEditingViewController * Login=[[TheEditingViewController alloc]init];
        Login.type=@"userName";
        Login.userNameStr=[NSString stringWithFormat:@"%@",userName];
        Login.sexStr=[NSString stringWithFormat:@"%@",sex];
        Login.memoStr=[NSString stringWithFormat:@"%@",@""];
        Login.titleName=@"姓名";
        Login.delegate=self;
        [self.navigationController pushViewController:Login animated:YES];
        
    }
    if ([cell.textLabel.text isEqualToString:@"性别"]) {
        TheEditingViewController * Login=[[TheEditingViewController alloc]init];
        Login.type=@"sex";
        Login.userNameStr=[NSString stringWithFormat:@"%@",userName];
        Login.sexStr=[NSString stringWithFormat:@"%@",sex];
        Login.memoStr=[NSString stringWithFormat:@"%@",@""];
        Login.titleName=@"性别";
        Login.delegate=self;
        [self.navigationController pushViewController:Login animated:YES];
    }
    if ([cell.textLabel.text isEqualToString:@"修改密码"]) {
        UpdateThePasswordViewController*detailViewController = [[UpdateThePasswordViewController alloc] init];
        [self.navigationController pushViewController:detailViewController animated:YES];
        }
    
    
    if ([cell.textLabel.text isEqualToString:@"手机号"]) {
        
        ForgotPasswordViewController *detailViewController = [[ForgotPasswordViewController alloc] init];
        detailViewController.titleName=@"换绑手机";
//        detailViewController.delegate = self;
        [self.navigationController pushViewController:detailViewController animated:YES];
        
    }

}
-(void)addProduct:(UIButton*)sender{

    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
    [params setValue:headImage forKey:@"headImage"];
    [params setValue:userName forKey:@"userName"];
    [params setValue:sex forKey:@"sex"];
    
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData1:@"Common/UpdateUser" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            
            NSLog(@"33333333====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"changeTokenId" object:nil];
//                [mDelegate update:@"update"];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
                [self.navigationController popViewControllerAnimated:YES];
                }else{
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];
    
}


#pragma mark portraitImageView getter
#define ORIGINAL_MAX_WIDTH 640

- (void)editPortrait {
    
    NSUserDefaults *user11 = [NSUserDefaults standardUserDefaults];
    NSString* Token11 = [user11 objectForKey:@"tokenId"];
    NSMutableDictionary *params11 = [NSMutableDictionary new];
    [params11 setValue:Token11 forKey:@"tokenId"];
    [params11 setValue:@"member" forKey:@"uploadType"];
    
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"Common/GetUpyunFormParams" params:params11 success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                NSLog(@"%@",severDataDict.dataDict);
                
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                NSString*policy=[severDataDict.dataDict objectForKey:@"policy"];
                NSString*signature=[severDataDict.dataDict objectForKey:@"signature"];
                NSString*action=[severDataDict.dataDict objectForKey:@"action"];
                [user setObject:signature forKey:@"signature"];
                [user setObject:policy forKey:@"policy"];
                [user setObject:action forKey:@"action"];
                [user synchronize];
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];
    
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.view];
}

#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    
    
    NSLog(@"%@",editedImage);
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        // TO DO
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            controller.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
        
    } else if (buttonIndex == 1) {
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
        
        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, ScreenWidth, ScreenWidth) limitScaleRatio:1];
        
        NSLog(@"%@",portraitImg);
        
        
        self.sendImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        UpYun *uy = [[UpYun alloc] init];
        uy.successBlocker = ^(id data)
        {
            
            [Global hideProgressHUDInternal:self.view];
            NSLog(@"%@",[data objectForKey:@"url"]);
            
            headImage=[data objectForKey:@"url"];
            [imageView setImage:portraitImg forState:UIControlStateNormal];
            
            
            
        };
        uy.failBlocker = ^(NSError * error)
        {
            [Global hideProgressHUDInternal:self.view];
            
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"上传失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            NSLog(@"%@",error);
        };
        uy.progressBlocker = ^(CGFloat percent, long long requestDidSendBytes)
        {
            
        };
        
        
        [uy uploadFile:portraitImg saveKey:[self getSaveKey]];
        
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            
        }];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}

#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return nil;
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}


-(void)idname{
    
    
    UIActionSheet *ac = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"用户相册", nil];
    [ac showInView:self.view];
    
}

-(NSString * )getSaveKey {
    /**
     *	@brief	方式1 由开发者生成saveKey
     */
    NSDate *d = [NSDate date];
    return [NSString stringWithFormat:@"/%d/%d/%.0f.png",[self getYear:d],[self getMonth:d],[[NSDate date] timeIntervalSince1970]];
    
    /**
     *	@brief	方式2 由服务器生成saveKey
     */
    //    return [NSString stringWithFormat:@"/{year}/{mon}/{filename}{.suffix}"];
    
    /**
     *	@brief	更多方式 参阅 http://wiki.upyun.com/index.php?title=Policy_%E5%86%85%E5%AE%B9%E8%AF%A6%E8%A7%A3
     */
    
}

- (int)getYear:(NSDate *) date{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSYearCalendarUnit;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    int year=[comps year];
    return year;
}

- (int)getMonth:(NSDate *) date{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSMonthCalendarUnit;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    int month = [comps month];
    return month;
}
-(UIImage *)imageCompress:(UIImage *)image
{
    UIImage *comImage=image;
    NSData * sendImageData = UIImageJPEGRepresentation(comImage, 1.0);
    NSUInteger sizeOrigin = [sendImageData length];
    NSUInteger sizeOriginKB = sizeOrigin / 1024;
    
    if (sizeOriginKB >800) {
        float a = 80.0000;
        float b = (float)sizeOriginKB;
        float q = sqrtf(a / b);
        
        CGSize sizeImage = [comImage size];
        CGFloat widthSmall = sizeImage.width * q;
        CGFloat heighSmall = sizeImage.height * q;
        CGSize sizeImageSmall = CGSizeMake(widthSmall, heighSmall);
        
        UIGraphicsBeginImageContext(sizeImageSmall);
        CGRect smallImageRect = CGRectMake(0, 0, sizeImageSmall.width, sizeImageSmall.height);
        [image drawInRect:smallImageRect];
        UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        NSData *dataImage = UIImageJPEGRepresentation(smallImage, 1.0);
        sendImageData = dataImage;
        NSLog(@"11111111%f",sizeImageSmall.width);
        NSLog(@"11111111%f",sizeImageSmall.height);
        comImage= smallImage;
        // [_imageview1.image retain];
    }
    return comImage;
}

@end
